import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';

/// 网络状态工具类
class NetworkUtils {
  static final Connectivity _connectivity = Connectivity();

  /// 检查网络连接状态
  static Future<bool> isConnected() async {
    try {
      final connectivityResult = await _connectivity.checkConnectivity();

      // 如果没有网络连接
      if (connectivityResult == ConnectivityResult.none) {
        return false;
      }

      // 进一步验证网络连接（ping测试）
      return await _hasInternetConnection();
    } catch (e) {
      return false;
    }
  }

  /// 获取网络连接类型
  static Future<ConnectivityResult> getConnectivityType() async {
    try {
      return await _connectivity.checkConnectivity();
    } catch (e) {
      return ConnectivityResult.none;
    }
  }

  /// 获取网络状态描述
  static Future<String> getNetworkStatusDescription() async {
    final connectivityResult = await getConnectivityType();

    switch (connectivityResult) {
      case ConnectivityResult.wifi:
        final hasInternet = await _hasInternetConnection();
        return hasInternet ? 'WiFi已连接' : 'WiFi已连接但无法访问互联网';
      case ConnectivityResult.mobile:
        final hasInternet = await _hasInternetConnection();
        return hasInternet ? '移动网络已连接' : '移动网络已连接但无法访问互联网';
      case ConnectivityResult.ethernet:
        final hasInternet = await _hasInternetConnection();
        return hasInternet ? '以太网已连接' : '以太网已连接但无法访问互联网';
      case ConnectivityResult.none:
        return '无网络连接';
      default:
        return '网络状态未知';
    }
  }

  /// 检查是否真正有互联网连接（ping测试）
  static Future<bool> _hasInternetConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com')
          .timeout(const Duration(seconds: 3));
      return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      // 如果google.com不可达，尝试其他域名
      try {
        final result = await InternetAddress.lookup('baidu.com')
            .timeout(const Duration(seconds: 3));
        return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
      } on SocketException catch (_) {
        return false;
      }
    } catch (_) {
      return false;
    }
  }

  /// 监听网络状态变化
  static Stream<ConnectivityResult> get onConnectivityChanged {
    return _connectivity.onConnectivityChanged;
  }
}
